package com.health.mapp.impl;

import io.rong.models.TokenReslut;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.health.commons.MD5Password;
import com.health.commons.PropertiesService;
import com.health.db.model.ImMsgNotice;
import com.health.db.model.ImMsgNoticeExample;
import com.health.db.model.UserCollectFavorite;
import com.health.db.model.UserLIST;
import com.health.db.model.UserLISTTemp;
import com.health.db.model.UserLoginJournal;
import com.health.db.model.UserRecommRemark;
import com.health.db.service.msg.IUserLoginJournalService;
import com.health.db.service.msg.ImMsgNoticeService;
import com.health.db.service.sm.IRongService;
import com.health.db.service.user.IUserCollectFavoriteService;
import com.health.db.service.user.IUserLISTService;
import com.health.db.service.user.IUserRecommRemarkService;
import com.health.mapp.bean.Header;
import com.health.mapp.bean.RegisterReq;
import com.health.mapp.bean.RegisterResp;
import com.health.mapp.utils.Constant;
import com.health.mapp.utils.DateUtils;
import com.health.mapp.utils.Response;
import com.health.mapp.utils.ResultCode;

/**
 * 注册接口
 * 		appId=12345679&version=1.0&method=register&timestamp=20121212154843&uuId=05ae94531ed53d89ff5da71d6f2ad780366a4eb9&memberid=1&sign=2976b2f3db9530e0de8097c1c912550f&lang=zh-Hans00000000000000000
 * 			{"userPhone":"13810570675","userName":"13810570675","password":"123456"}
 * @author HiRoad
 *
 */
public class RegisterImpl implements ActionInterface {
	
	private IUserLISTService userLISTService  ;
	private IRongService rongService;
	private ImMsgNoticeService imMsgNoticeService  ;
	private IUserLoginJournalService userLoginJournalService;
	private IUserRecommRemarkService userRecommRemarkService;
	
    private IUserCollectFavoriteService userCollectFavoriteService ;
	@Override
	public Response execute(Header header, Object reqBean) throws Exception {
		
		RegisterReq req=(RegisterReq) reqBean;
		//do it bobo
		RegisterResp _resp= new RegisterResp();
		
		if (StringUtils.isBlank(req.getUserPhone())
			||StringUtils.isBlank(req.getUserName())
			||StringUtils.isBlank(req.getPassword())){
			
			_resp.setErrorCode(ResultCode.OPERATION_LAKE_PARAMETER_ERROR);
			_resp.setErrorMsg(ResultCode.OPERATION_LAKE_PARAMETER_ERROR_NOTE);
			return _resp;
		}

		//String remoteIP=SecureUtil.getRemoteHost((HttpServletRequest) header.getHttpRequest());
		
		ImMsgNoticeExample notice = new ImMsgNoticeExample();
		notice.setNoticeReceiveAddress(req.getUserPhone());
		notice.setIsUsedFlag((short) -1);
		notice.setCreateDate(DateUtils.getDateAfterSecond(DateUtils.now(),-5));
		
		List<ImMsgNotice> list=imMsgNoticeService.selectByExample(notice);
		 
		if (null==list|| list.size()==0) {
			
			_resp.setErrorCode(ResultCode.UN_VERIFY_SMS_ERROR);
			_resp.setErrorMsg(ResultCode.UN_VERIFY_SMS_ERROR_NOTE);
			return _resp;
		}
		
		//check the userid
		UserLIST user=userLISTService.selectByUserNo(req.getUserPhone());
		UserLIST  userLIST =new UserLIST();
		UserLISTTemp  returnUserBean =new UserLISTTemp();
		Date now =DateUtils.now();
		
		//可以注册
		if (null==user) {
			
			long userLoginResult=-1;
			
			//userLIST.setUserAlias("");
			userLIST.setUserName(req.getUserName());
			userLIST.setApptoken("");
			userLIST.setUserNo(req.getUserPhone());
			userLIST.setPasswordCreateDate(now);
			userLIST.setLoginDatetime(now);
			userLIST.setLogoutDatetime(now);
			userLIST.setPassword(MD5Password.getEncodedPassword_Hex(req.getPassword()));
			userLIST.setCreateDate(now);
			userLIST.setUpdateDate(now);
			userLIST.setRegisterDate(now);
			userLIST.setMachinedeviceid(header.getUuId());
			
			//user :1 doctor:3
			userLIST.setTypeid(1);
			userLIST.setTypeName("用户");
			userLIST.setIsUsedFlag((short) 1);
			//user/userdefault.png日
			userLIST.setIconUrl(PropertiesService.getString("iconUrl.userDefaultUrl").trim());
			//userLIST.setRunstatusid((short)2);
			if (StringUtils.isNotBlank(req.getBusinessCode())) {
				userLIST.setComment(req.getBusinessCode());
			}
		
			//check the userid
			//register_gift_cardType
			if (StringUtils.isNotBlank( PropertiesService.getString("register_gift_cardType").trim())) {
				 userLoginResult=userLISTService.insertUser(userLIST,Long.valueOf(PropertiesService.getString("register_gift_cardType").trim()));
			}else{
				 userLoginResult=userLISTService.insertUser(userLIST);
			}
				
			returnUserBean.setUserId(String.valueOf(userLIST.getUserid()));
			returnUserBean.setUserName(userLIST.getUserName());
			returnUserBean.setUserPhone(userLIST.getUserNo());
			returnUserBean.setRegTime(now);
			returnUserBean.setIcon(userLIST.getIconUrl());
			//先做唯一性校验
		}else{
			
			//1为旧线下用户，不提供登录。用户注册，更新原表中的注册信息
			Short isExportFlag = user.getIsExportFlag();
			if (null!=isExportFlag&&1==isExportFlag.intValue()) {
				
				user.setPassword(MD5Password.getEncodedPassword_Hex(req.getPassword()));
				user.setPasswordCreateDate(DateUtils.now());
				if (StringUtils.isNotBlank(req.getBusinessCode())) {
					user.setComment(req.getBusinessCode());
				}
				user.setRegisterDate(now);
				userLISTService.updatePassword(user);
				
				returnUserBean.setUserId(String.valueOf(user.getUserid()));
				returnUserBean.setUserName(user.getUserName());
				returnUserBean.setUserPhone(user.getUserNo());
				returnUserBean.setRegTime(now);
				returnUserBean.setIcon(user.getIconUrl());
				
			}else{
				_resp.setErrorCode(ResultCode.LOGIN_FAIL_MEMBER_NAME_IS_EXISTS);
				_resp.setErrorMsg(ResultCode.LOGIN_FAIL_MEMBER_NAME_IS_EXISTS_NOTE);
				return _resp;
			}
		}
			/**
			 * token为空的话重新从融云获取Token
			 * */
			TokenReslut tokenReslut=rongService.getUserToken(String.valueOf(returnUserBean.getUserId()), returnUserBean.getUserName(), PropertiesService.getString("iconUrl.userDefaultUrl").trim());
			if(null!=tokenReslut&&tokenReslut.getCode()==200)
			{
				_resp.setErrorCode(ResultCode.OPERATION_SUCCESS);
				_resp.setErrorMsg("Success");
				_resp.setToken(tokenReslut.getToken());
				
			}else {
				_resp.setErrorCode(-1);
				_resp.setErrorMsg("获取Token失败");
			}
		 
		 
		_resp.setErrorCode(ResultCode.OPERATION_SUCCESS);
		_resp.setErrorMsg(ResultCode.OPERATION_SUCCESS_NOTE);
		
 
		_resp.setUser(returnUserBean);
		
		
		UserLoginJournal loginJournal = new UserLoginJournal();

		loginJournal.setUserid(Long.valueOf(returnUserBean.getUserId()));
		loginJournal.setMachinedeviceid(header.getUuId());
		loginJournal.setLoginDatetime(DateUtils.now());

		userLoginJournalService.insert(loginJournal);
		
		
		collectDoc(returnUserBean.getUserId(), req.getBusinessCode(), req.getUserPhone());
		
		// TODO Auto-generated method stub
		return _resp;
	}
	
	private void collectDoc(String userId,String businessCode,String userPhone){
		
			List<UserRecommRemark> recomList=  userRecommRemarkService.selectByUserPhone( userPhone);
			
			if (StringUtils.isBlank(businessCode) ){
				return;
			}
			List<UserLIST > userList= userLISTService.selectByBusinessCode(businessCode);
		    Long collectorId = Long.valueOf(userId);
			//推荐码
			Long collectionId1 =0l;
			
			if (userList.size()==1) {
				UserLIST user = userList.get(0);
				
				if (user.getTypeid().intValue() == Constant.CONSTANTS_USER_ROLE_ID_3.intValue()) {
					  collectionId1 = user.getUserid();
					
					  UserCollectFavorite userCollectFavorite = userCollectFavoriteService.selectByCollectorIdAndCollectionId(collectorId,collectionId1);
				      UserLIST doctor = userLISTService.selectByUserId(collectionId1);
				        //收藏
				            if(null==userCollectFavorite ){
				            
				            UserCollectFavorite newCollection = new UserCollectFavorite();
				            newCollection.setCollectorid(collectorId);
				            Date now = new Date();
				            newCollection.setCollectDate(now);
				            newCollection.setCollectionid(collectionId1);
				            newCollection.setCollectionName(doctor.getUserName());
				            newCollection.setCreateDate(now);
				            newCollection.setUpdateDate(now);
				            newCollection.setUpdateUserid(collectorId);
				            userCollectFavoriteService.insert(newCollection);
				      }
				}
			}
			
			Long collectionId2 =0l;
			if (recomList.size()>0) {
				
				UserRecommRemark recom = recomList.get(0);
				
				if (StringUtils.isNotBlank(recom.getBusinessCode())&&StringUtils.isNumeric(recom.getBusinessCode())) {
					
					 collectionId2 = Long.valueOf(recom.getBusinessCode());
					 
					 if (collectionId1.longValue()!=collectionId2.longValue()) {
					
					  UserCollectFavorite userCollectFavorite = userCollectFavoriteService.selectByCollectorIdAndCollectionId(collectorId,collectionId2);
				      UserLIST doctor = userLISTService.selectByUserId(collectionId2);
				        //收藏
				            if(null==userCollectFavorite ){
				            
				            UserCollectFavorite newCollection = new UserCollectFavorite();
				            newCollection.setCollectorid(collectorId);
				            Date now = new Date();
				            newCollection.setCollectDate(now);
				            newCollection.setCollectionid(collectionId2);
				            newCollection.setCollectionName(doctor.getUserName());
				            newCollection.setCreateDate(now);
				            newCollection.setUpdateDate(now);
				            newCollection.setUpdateUserid(collectorId);
				            userCollectFavoriteService.insert(newCollection);
				      }
					 }
				}
				
			}
			
		
		
	        //Long collectionId =  Long.parseLong(docId);
	      
	}
	
	public IUserLISTService getUserLISTService() {
		return userLISTService;
	}
	public void setUserLISTService(IUserLISTService userLISTService) {
		this.userLISTService = userLISTService;
	}
	/**
	 * @return the rongService
	 */
	public IRongService getRongService() {
		return rongService;
	}
	/**
	 * @param rongService the rongService to set
	 */
	public void setRongService(IRongService rongService) {
		this.rongService = rongService;
	}
	/**
	 * @return the imMsgNoticeService
	 */
	public ImMsgNoticeService getImMsgNoticeService() {
		return imMsgNoticeService;
	}
	/**
	 * @param imMsgNoticeService the imMsgNoticeService to set
	 */
	public void setImMsgNoticeService(ImMsgNoticeService imMsgNoticeService) {
		this.imMsgNoticeService = imMsgNoticeService;
	}
	
	public IUserLoginJournalService getUserLoginJournalService() {
		return userLoginJournalService;
	}
	public void setUserLoginJournalService(
			IUserLoginJournalService userLoginJournalService) {
		this.userLoginJournalService = userLoginJournalService;
	}
	public IUserRecommRemarkService getUserRecommRemarkService() {
		return userRecommRemarkService;
	}
	public void setUserRecommRemarkService(
			IUserRecommRemarkService userRecommRemarkService) {
		this.userRecommRemarkService = userRecommRemarkService;
	}
	public IUserCollectFavoriteService getUserCollectFavoriteService() {
		return userCollectFavoriteService;
	}
	public void setUserCollectFavoriteService(
			IUserCollectFavoriteService userCollectFavoriteService) {
		this.userCollectFavoriteService = userCollectFavoriteService;
	}
	
}
